const qs = require("qs");
const Wechat = require("jweixin-module");
const globalConfig = require("@/config");
const httpModule = require("@/modules/http");
export default {
  methods: {
    //获取appid
    getWeChatConfig() {
      return httpModule.httpGet({
        url: "/wechat/config",
        data: {
          url: window.location.href.split("#")[0],
        },
        loading: false,
      });
    },
    // 跳转授权
    wechatAnthoration({ scope, state, appid, customHash, customHashSearch }) {
      const { hash, origin, pathname } = location;
      const nextHash = customHash || hash;
      const [hashUrl, hashSearch] = nextHash.split("?");
      const newHash = customHashSearch
        ? hashUrl + "?" + customHashSearch
        : hashUrl;
      const newHref = origin + pathname + newHash;
      const redirect_uri = encodeURIComponent(newHref);
      window.location =
        "https://open.weixin.qq.com/connect/oauth2/authorize" +
        "?appid=" +
        appid +
        "&redirect_uri=" +
        redirect_uri +
        "&response_type=code" +
        "&scope=" +
        scope +
        "&state=" +
        state +
        "#wechat_redirect"; //引导用户授权
    },
    //微信环境判断
    isWeChat() {
      //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
      const ua = window.navigator.userAgent.toLowerCase();
      //通过正则表达式匹配ua中是否含有MicroMessenger字符串
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
      } else {
        document.title = "抱起，出错了";
        let link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = "https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css";
        let head = document.getElementsByTagName("head")[0];
        head.appendChild(link);
        document.body.innerHTML =
          '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
        return false;
      }
    },
    // 微信配置初始化
    wechatInit() {
      return new Promise((resolve, reject) => {
        if (this.isWeChat()) {
          this.getWeChatConfig()
            .then((res) => {
              Wechat.config({
                ...res.data,
              });
              Wechat.ready(function () {
                console.log("wx config success");
                /* 暴露微信对象 */
                resolve(wx);
              });
              Wechat.error(function (err) {
                console.log("wx config error");
                reject(err);
              });
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },
    // 微信配置登录
    /* 
        forceAuto 
        在params获取code的情况下 是否强制刷新code
        
    */
    wechatLogin(loginParams) {
      /* 
            scope = "snsapi_base" , state = 0  静默获取
            scope = "snsapi_userinfo" , state = 1  铭文获取
        */
      const {
        forceAuto = false,
        scope = "snsapi_base",
        state = 0,
        customHash,
        customHashSearch,
      } = loginParams;
      return new Promise((resolve, reject) => {
        if (this.isWeChat()) {
          // 获取code
          const search = location.search;
          const searchParams = search ? search.split("?")[1] : search;
          if (!forceAuto && searchParams && qs.parse(searchParams).code) {
            const { code, state } = qs.parse(searchParams);
            resolve({
              code,
              state: state - 0,
            });
          } else {
            if (globalConfig.appid) {
              this.wechatAnthoration({
                appid: globalConfig.appid,
                scope,
                state,
                customHash,
                customHashSearch,
              });
            }
          }
        } else {
          reject();
        }
      });
    },
  },
};
